package com.yupi.springbootinit.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.yupi.springbootinit.annotation.AuthCheck;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.DeleteRequest;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.constant.UserConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.model.dto.book.BookAddRequest;
import com.yupi.springbootinit.model.dto.book.BookEditRequest;
import com.yupi.springbootinit.model.dto.book.BookQueryRequest;
import com.yupi.springbootinit.model.dto.book.BookUpdateRequest;
import com.yupi.springbootinit.model.entity.Book;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.vo.BookVO;
import com.yupi.springbootinit.service.BookService;
import com.yupi.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 帖子接口
 *
 * @author wzh
 */
@RestController
@RequestMapping("/book")
@Slf4j
public class BookController {

    @Resource
    private BookService bookService;

    @Resource
    private UserService userService;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param bookAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addBook(@RequestBody BookAddRequest bookAddRequest, HttpServletRequest request) {
        if (bookAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Book book = new Book();
        BeanUtils.copyProperties(bookAddRequest, book);
        User loginUser = userService.getLoginUser(request);
        boolean result = bookService.save(book);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newBookId = book.getId();
        return ResultUtils.success(newBookId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteBook(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Book oldBook = bookService.getById(id);
        ThrowUtils.throwIf(oldBook == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
 /*       if (!oldBook.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }*/
        boolean b = bookService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param bookUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateBook(@RequestBody BookUpdateRequest bookUpdateRequest) {
        if (bookUpdateRequest == null || bookUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Book book = new Book();
        BeanUtils.copyProperties(bookUpdateRequest, book);
        // 参数校验
        long id = bookUpdateRequest.getId();
        // 判断是否存在
        Book oldbook = bookService.getById(id);
        ThrowUtils.throwIf(oldbook == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = bookService.updateById(book);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<Book> getBookVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Book book = bookService.getById(id);
        if (book == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(book);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param bookQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<BookVO>> listBookVOByPage(@RequestBody BookQueryRequest bookQueryRequest,
            HttpServletRequest request) {
        long current = bookQueryRequest.getCurrent();
        long size = bookQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Book> bookPage = bookService.page(new Page<>(current, size),
                bookService.getQueryWrapper(bookQueryRequest));
        return ResultUtils.success(bookService.getBookVOPage(bookPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param bookQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<BookVO>> listMyBookVOByPage(@RequestBody BookQueryRequest bookQueryRequest,
            HttpServletRequest request) {
        if (bookQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
  /*      bookQueryRequest.setUserId(loginUser.getId());*/
        long current = bookQueryRequest.getCurrent();
        long size = bookQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Book> bookPage = bookService.page(new Page<>(current, size),
                bookService.getQueryWrapper(bookQueryRequest));
        return ResultUtils.success(bookService.getBookVOPage(bookPage, request));
    }

    // endregion


    /**
     * 编辑（用户）
     *
     * @param bookEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editBook(@RequestBody BookEditRequest bookEditRequest, HttpServletRequest request) {
        if (bookEditRequest == null || bookEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Book book = new Book();
        BeanUtils.copyProperties(bookEditRequest, book);
        // 参数校验
        User loginUser = userService.getLoginUser(request);
        long id = bookEditRequest.getId();
        // 判断是否存在
        Book oldBook = bookService.getById(id);
        ThrowUtils.throwIf(oldBook == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
/*        if (!oldBook.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }*/
        boolean result = bookService.updateById(book);
        return ResultUtils.success(result);
    }

}
